﻿using SmartHRMS.Infrastructure;
using SmartHRMS.Infrastructure.Caching;
using SmartHRMS.Model.Account;
using System;
using System.Collections.Generic;

namespace SmartHRMS.Services
{
    public class RoleService : IRoleService
    {
        private IRoleRepository _RoleRepository;

        private IUnitOfWork _UnitOfWork;

        private ICacheStorage _CacheStorage;

        string storageCacheKey = "roles";

        public RoleService(IRoleRepository roleRepository, IUnitOfWork UnitOfWork, ICacheStorage CacheStorage)
        {
            this._RoleRepository = roleRepository;
            this._CacheStorage = CacheStorage;
            this._RoleRepository.Inject(UnitOfWork);
            this._UnitOfWork = UnitOfWork;
        }

        #region IRoleService Members

        public IList<Role> FindAll()
        {
            IList<Role> roles;
            roles = _CacheStorage.Retrieve<List<Role>>(storageCacheKey);
            if (roles == null)
            {
                roles = _RoleRepository.FindAll();
                _CacheStorage.Store(storageCacheKey, roles);
            }
            return roles;
        }

        public Role FindBy(Guid roleId)
        {
            return _RoleRepository.FindBy(roleId);
        }

        public void Save(Role role)
        {

            if (role.RoleId != Guid.Empty)
            {
                _RoleRepository.RevokePermissions(role.RoleId);
            }
           
            _RoleRepository.Save(role);           

            _UnitOfWork.Commit();

            _CacheStorage.Remove(storageCacheKey);
        }

        public void Remove(Role role)
        {
            _RoleRepository.Remove(role);
            _CacheStorage.Remove(storageCacheKey);
        }

        public bool IsRoleNameExist(string userName)
        {
            return _RoleRepository.IsRoleNameExist(userName);
        }
        #endregion
    }
}
